const multer = require('multer');
const mime = require('mime');
const makeDir = require('make-dir');

function myMulter(options){
    // 用户可以自定上传目录
    options.path =  options.path || 'public/uploads/';
    // 用户可以自定上传文件的大小限制(默认1M)
    options.allowSize = options.allowSize || 1024 * 1024 
    // 用户可以自定上传允许的类型
    let allowMimes = [
        'image/jpeg',
        'image/png',
        'image/gif',
        'application/msword',
        'application/pdf',
        'text/plain',
        'application/zip',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ]
    options.allowMimes = options.allowMimes || allowMimes;

    let storage = multer.diskStorage({
        // 设置文件上传的目录
        destination: function (req, file, cb) {
            // 如果文件不存在，则创建它
            // 每月一个目录， 月份的目录放到年份目录下
            let d = new Date();
            // 文件想要保存的目录
            let path = options.path + d.getFullYear().toString() + '/' + (d.getMonth()+1).toString() + '/';
            if(makeDir.sync(path)){
                cb(null, path);
            }
        },
        filename: function (req, file, cb) {
            let randomStr = Math.floor(Math.random() * 100).toString();
            cb(null, randomStr + Date.now() + '.' + mime.getExtension(file.mimetype))
        }
    });

    return multer({
        storage: storage,
        limits: {
            // 默认文件大小为1M
            fileSize: options.allowSize
        },
        fileFilter: function (req, file, cb) {
            if (options.allowMimes.includes(file.mimetype)) {
                cb(null, true);
            } else {
                req.uploadError = '1000';
                cb(null, false);
            }
        }
    })
}

module.exports = {
    myMulter
}